/**
 * Copyright 2008 Frank van Lingen Licensed under the Apache License, Version
 * 2.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package superpodder.controller.feedreader;

import java.io.File;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import superpodder.controller.FeedDownloader;

import com.sun.syndication.feed.synd.SyndEnclosure;
import com.sun.syndication.feed.synd.SyndEnclosureImpl;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class Rome extends FeedReader {

    public Rome(FeedDownloader feedDownloader) {
        super(feedDownloader);
        System.out.println("Creating Rome feedreader");
    }

    public String[] extractPodCasts(String feedUrl, int amount)
            throws Exception {
        this.formatErrors = 0;
        final SyndFeedInput input = new SyndFeedInput();
        input.setXmlHealerOn(true);
        File f = new File(feedUrl);
        final SyndFeed feed = input.build(new XmlReader(f.toURI().toURL()));

        // System.out.println(feed);

        final List<SyndEntryImpl> entries = feed.getEntries();
        System.out.println("Found " + entries.size() + " entries");
        if (entries.size() == 0) {
            return new String[0];
        }

        System.out.println("Trying to sort entries found");
        Collections.sort(entries, new RomeComparator());
        System.out.println("Entries have been sorted");
        final Iterator<SyndEntryImpl> iterator = entries.iterator();

        final int maxFeeds = Math.min(amount, entries.size());
        int feedCounter = 0;

        final String[] feeds = new String[maxFeeds];

        for (int i = 0; i < maxFeeds; i++) {

            final SyndEntryImpl entry = iterator.next();

            List<SyndEnclosure> enclosures = entry.getEnclosures();
            Iterator<SyndEnclosure> iterator2 = enclosures.iterator();
            while (iterator2.hasNext()) {
                SyndEnclosure podcast = (SyndEnclosure) iterator2.next();

                String downloadLoc = podcast.getUrl();

                if (!rightFormat(downloadLoc)) {

                    String msg = new String(
                            " URL not right format or not encoded in right field");
                    this.feedDownloader.log("ROME: " + feedUrl + "--->"
                            + downloadLoc + msg
                            + " Trying something else (attempt 2)\n\n");

                    downloadLoc = entry.getLink();

                    if (!rightFormat(downloadLoc)) {
                        this.feedDownloader.log("ROME: " + feedUrl + "--->"
                                + downloadLoc + msg
                                + " Trying something else (attempt 3)\n\n");

                        final SyndEnclosureImpl syndEnclosureImpl = (SyndEnclosureImpl) entry
                                .getEnclosures().iterator().next();
                        downloadLoc = syndEnclosureImpl.getUrl();

                    }
                    if (!rightFormat(downloadLoc)) {
                        this.feedDownloader.log("ROME: " + feedUrl + "--->"
                                + downloadLoc + msg + "\n\n");
                        throw new Exception("url not encoded in right field");
                    }
                } else {

                    feeds[feedCounter] = downloadLoc;
                    feedCounter += 1;
                    if (feedCounter >= maxFeeds) {
                        break;
                    }
                }
                this.reachedMaxErrors();
            }
            if (feedCounter >= maxFeeds) {
                break;
            }
        }

        return feeds;
    }

}
